<template>
  <div class="note-publish">
    <div class="note-wrapper">
      <div class="note-cell">
        <van-field v-model="state.title" label="标题" placeholder="请输入标题" />
      </div>

      <div class="note-cell">
        <van-field label="上传图片">
          <template #input>
            <van-uploader v-model="state.img" :after-read="afterRead" maxCount="1" />
          </template>
        </van-field>
      </div>

      <div class="note-cell">
        <div class="sort" @click="state.sortShow = true">
          <span>选择分类</span>
          <span>{{ state.article_type }} <van-icon name="arrow" /></span>
        </div>
        <van-action-sheet
          v-model:show="state.sortShow"
          :actions="actions"
          @select="onSelect"
        />
      </div>
    </div>

    <div class="editor-container">
      <div ref="quillEditor" class="editor"></div>
      <input
        ref="fileInput"
        type="file"
        accept="image/*"
        @change="handleImageUpload"
        style="display: none"
      />
    </div>

    <div class="btn">
      <van-button type="primary" block @click="notePublish">发布文章</van-button>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { getCategoryList } from '@/api/category.ts';
import { articleAdd } from '@/api/article.ts';
import Quill from 'quill';
import 'quill/dist/quill.snow.css';
import ImageResize from 'quill-image-resize-module-plus';
import axios from 'axios';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
const quillEditor = ref(null);
const fileInput = ref(null);
const editorContent = ref('');
let quill = null;

// 注册 Quill 扩展模块
Quill.register('modules/imageResize', ImageResize);

const state = reactive({
  title: '',
  img: [],
  sortShow: false,
  article_type: '推荐',
  content: '',
});

const actions = reactive([]);

// 初始化富文本编辑器
onMounted(() => {
  const toolbarOptions = [
    [{ font: [] }],
    [{ size: ['small', false, 'large', 'huge'] }],
    ['bold', 'italic', 'underline', 'strike'],
    [{ color: [] }, { background: [] }],
    [{ header: 1 }, { header: 2 }, 'blockquote', 'code-block'],
    [{ list: 'ordered' }, { list: 'bullet' }],
    [{ align: [] }],
    ['link', 'image', 'video'],
    ['clean'],
  ];

  quill = new Quill(quillEditor.value, {
    theme: 'snow',
    modules: {
      toolbar: {
        container: toolbarOptions,
        handlers: {
          image: selectLocalImage,
        },
      },
      imageResize: {},
    },
    placeholder: '请输入内容...',
  });

  quill.on('text-change', () => {
    editorContent.value = quill.root.innerHTML;
    state.content = editorContent.value;
  });

  fetchCategories();
});

// 点击工具栏图片按钮
function selectLocalImage() {
  fileInput.value.click();
}

// 上传图片逻辑
async function handleImageUpload(event) {
  const file = event.target.files[0];
  if (!file) return;

  const formData = new FormData();
  formData.append('image', file);

  try {
    const res = await axios.post('/api/upload', formData, {
      headers: {
        token: userStore.token,
      },
    });

    if (res.data.code === 1) {
      const imageUrl = res.data.data;
      insertToEditor(imageUrl);
    } else {
      console.error('上传失败:', res.data.msg || '未知错误');
    }
  } catch (error) {
    console.error('上传异常:', error);
  }
}

// 插入图片到编辑器
function insertToEditor(url) {
  const range = quill.getSelection(true);
  if (range) {
    quill.insertText(range.index, '\n', 'user');
    quill.insertEmbed(range.index + 1, 'image', url, 'user');
    quill.insertText(range.index + 2, '\n', 'user');
  } else {
    quill.insertEmbed(quill.getLength(), 'image', url, 'user');
  }
}

// 获取分类
async function fetchCategories() {
  try {
    const res = await getCategoryList();
    if (res.data.code === 1) {
      actions.length = 0;
      res.data.data.forEach((category) => {
        actions.push({ name: category.categoryName });
      });
    }
  } catch (err) {
    console.error('获取分类失败:', err);
  }
}

// 分类选择
function onSelect(item) {
  state.sortShow = false;
  state.article_type = item.name;
}

// 上传图片回调（封面图）
function afterRead(file) {
  console.log('封面图上传文件：', file);
  // 可选：你可以在这里上传封面图
}

// 发布文章
async function notePublish() {
  try {
    const article = {
      title: state.title,
      categoryId: '', // 分类ID，根据 article_type 匹配转换
      coverImg: state.img.length > 0 ? state.img[0].content || state.img[0].url : '',
      content: state.content,
      state: '已发布',
    };

    const res = await articleAdd(article);
    const response = res.data;

    if (response.code === 1) {
      console.log('文章发布成功');
    } else {
      console.error('发布失败:', response.msg);
    }
  } catch (err) {
    console.error('发布异常:', err);
  }
}
</script>

<style lang="less">
.note-publish {
  min-height: 100vh;
  margin-top: 45px;
  padding: 16px;

  .note-wrapper {
    background-color: #fff;
    border-radius: 8px;
    padding: 16px;
  }

  .note-cell {
    border-bottom: 1px solid #eee;

    .sort {
      display: flex;
      justify-content: space-between;
      line-height: 3;
      padding: 10px 18px;
      font-size: 14px;
      color: #323233;
    }
  }

  .editor-container {
    margin-top: 20px;
    background: #fff;
    border-radius: 8px;
    border: 1px solid #ddd;
    padding: 10px;
  }

  .editor {
    min-height: 300px;
  }

  .ql-toolbar {
    position: sticky;
    top: 0;
    background: #fff;
    z-index: 10;
  }

  .btn {
    width: 80%;
    margin: 30px auto 0;
  }
}
</style>
